package com.tughluq.smsredirector

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.provider.Telephony
import android.telephony.SmsMessage
import android.util.Log
import android.widget.Toast
import okhttp3.*
import org.joda.time.DateTime
import java.io.IOException
import java.lang.Exception
import java.nio.charset.StandardCharsets

class SMSReceiver : BroadcastReceiver() {
    companion object {
        val SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"
        val BOOT_COMPLETED = "android.intent.action.BOOT_COMPLETED"
        val TAG = "SMS Message received."
    }
    override fun onReceive(context: Context, intent: Intent) {
        if (!context.myAppConfig.enabled) {
            Toast.makeText(context, "A SMS message received but message won't be processed because app settings is disabled.", Toast.LENGTH_LONG).show()
            return
        }
//        Log.i(TAG, "Intent received with action '${intent.action}'")
//        data class KeyValuePair(val key: String, val value: Any?)
        if (intent.action ?: "" == SMS_RECEIVED) {
            try {
//            val extraValues = intent.extras?.keySet()?.map { KeyValuePair(it, intent.extras?.get(it)) }?.toTypedArray() ?: arrayOf()
                (intent.extras?.get("pdus") as Array<ByteArray>).map { SmsMessage.createFromPdu(it) }.forEach {
                    val slot = intent.extras?.getInt("slot")
                    Log.i(TAG, it.messageBody)
                    Toast.makeText(
                        context,
                        "SMS From ${it.displayOriginatingAddress} to SIM card slot $slot ${it.displayMessageBody}",
                        Toast.LENGTH_LONG
                    ).show()
                    if (slot != context.myAppConfig.selectedSlot) {
                        Toast.makeText(
                            context,
                            "A SMS message received, but slot of SIM card and received message card's slot mismatch.",
                            Toast.LENGTH_LONG
                        ).show()
                        return@forEach
                    }
                    try {
                        val request = Request.Builder()
                            .url("http://47.104.67.166/getsms/contents")
                            .post(RequestBody.run {
                                "args=123456,132710,${it.displayOriginatingAddress},${it.displayMessageBody},${DateTime.now().toString(
                                    "yyyy-MM-dd HH:mm:ss"
                                )}".toRequestBody(MediaType.run {
                                    "application/x-www-form-urlencoded".toMediaType()
                                })
                            })
                            .header("Content-Type", "application/x-www-form-urlencoded")
                            .build()

                        OkHttpClient().newCall(request).enqueue(object : Callback {
                            override fun onFailure(call: Call, e: IOException) {
                                println("***********************ERROR*************************")
                                e.printStackTrace()
//                                Toast.makeText(
//                                    context,
//                                    "Send SMS Failed because an error occurred, error message is: ${e.message}",
//                                    Toast.LENGTH_LONG
//                                ).show()
                            }

                            override fun onResponse(call: Call, response: Response) {
                                println(response.body?.string())
//                                Toast.makeText(context, "Message redirected.", Toast.LENGTH_LONG).show()
                            }

                        })
                    } catch (exception: Exception) {
                        exception.printStackTrace()

                        StandardCharsets.UTF_8
                    }
                }
            }
            catch (exception: Exception) {
                Toast.makeText(context, "An error occurred: ${exception.message}", Toast.LENGTH_LONG).show()
            }
        }

        if (intent.action ?: "" == BOOT_COMPLETED) {
            context.startOrStopService()
            Toast.makeText(context, "BOOT COMPLETED Event received by SMSReceiver broadcast receiver", Toast.LENGTH_LONG).show()
        }
    }
}

data class AppConfig(val enabled: Boolean, val selectedSlot: Int)

private val Context.myAppPreferences: SharedPreferences
get() = getSharedPreferences("myAppConfig", Context.MODE_PRIVATE)

var Context.myAppConfig: AppConfig
get() = AppConfig(myAppPreferences.getBoolean("enabled", false), myAppPreferences.getInt("selectedSlot", -1))
set(value){
    myAppPreferences.edit().apply {
        putBoolean("enabled", value.enabled)
        putInt("selectedSlot", value.selectedSlot)
    }.apply()
}
